package the.one.weather.presenter;

import android.text.TextUtils;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import the.one.base.base.presenter.BasePresenter;
import the.one.base.util.JsonUtil;
import the.one.net.util.FailUtil;
import the.one.weather.model.Weather;
import the.one.weather.view.WeatherView;


//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛

/**
 * @author The one
 * @date 2019/5/7 0007
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
public class WeatherPresenter extends BasePresenter<WeatherView> {

    private static final String TAG = "WeatherPresenter";

    private static final String API = "http://api.map.baidu.com/telematics/v3/weather";

    public void getWeatherInfo(final Weather weather){
        if(TextUtils.isEmpty(weather.getCurrentCity()))return;
        OkHttpUtils.get()
                .url(API)
                .addParams("location", weather.getCurrentCity())
                .addParams("output", "json")
                .addParams("ak", "T2AHbrsEn5FaSg4Iir8YfP1U")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if(isViewAttached()){
                            getView().showFailTips(FailUtil.getFailString(e));
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if(isViewAttached()){
                            parseJson(weather,response);
                        }
                    }
                });
    }

    private void parseJson(Weather weather,String response){
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(response);
            int error = jsonObject.getInt("error");
            String msg = jsonObject.getString("status");
            if(error == 0){
                String result = jsonObject.getString("results");
                result = result.substring(1,result.length()-1);
                Weather temp = JsonUtil.fromJson(result,Weather.class);
                weather.setFutures(temp.getFutures());
                weather.setTips(temp.getTips());
                weather.initWeather();
                getView().onSuccess(weather);
            }else{
                getView().showFailTips(msg);
            }
        }catch (JSONException e){
            getView().showFailTips("数据解析错误");
        }
    }

}
